/**
 * 
 */
package com.ideeli.webextractor.service;

import java.util.List;

import org.apache.log4j.Logger;

import com.ideeli.webextractor.dao.ProductDao;
import com.ideeli.webextractor.domain.Product;
import com.ideeli.webextractor.domain.ProductDetail;
import com.ideeli.webextractor.utils.Utility;

/**
 * @author spaida
 * 
 */
public class PriceChangeServiceImpl implements PriceChangeService {

	private static final Logger logger = Logger.getLogger(PriceChangeServiceImpl.class);
	
	private ProductDao productDao;
	
	private CacheService cacheService;

	@Override
	public void chgPerCategory(String inputFileName) {

		logger.warn("chgPerCategory");
		logger.warn("reading file " + inputFileName);

		String fileContent = Utility.readFile(inputFileName);
		String[] records = fileContent.split("\n");

		for (String record : records) {
			String[] rec = record.split(",");
			try {
				int catId = productDao.findCategoryIdByName(rec[0].trim());
				if (catId == -1) {
					logger.warn("Category not found: " + record);
					continue;
				}
				
				String sql="select p.product_id as product_id, pp.base_price as base_price, pp.profit_percent as profit_percent, p.sku as sku, tax  from product p, product_to_category pc,  product_price pp" 
					+" where pc.category_id="+catId  
					+" and p.product_id=pc.product_id"
					+" and p.product_id=pp.product_id";


				List<Product> products = productDao.loadProuctsPrice(sql);
				logger.warn("No of prods found: " + products.size());
				for (Product product : products) {
					float pp = Float.parseFloat(rec[1]);
					logger.warn("applying new pp :" + pp);

					float basePriceWithGST = product.getBase_price()* (1 + product.getTax() / 100);
					float finalPrice = basePriceWithGST * (1 + pp / 100);
					logger.warn("calculated final price: " + finalPrice);
					productDao.updatePrice(product.getProduct_id(), finalPrice, pp,product.getBase_price());
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}

	public void flatPercentageChgToAll(float percentage) throws Exception 
	{
		logger.warn("flatPercentageChgToAll");
		logger.warn("applying new pp :" + percentage);

		String sql="select p.product_id as product_id, pp.base_price as base_price, pp.profit_percent as profit_percent, p.sku as sku, tax  " +
				"from product p, product_price pp" 
			+" where p.product_id=pp.product_id";
		
		List<Product> products = productDao.loadProuctsPrice(sql);
		logger.warn("No of prods found: " + products.size());
		for (Product product : products) 
		{

			float basePriceWithGST = product.getBase_price() * (1 + product.getTax() / 100);
			float finalPrice = basePriceWithGST * (1 + percentage / 100);
			logger.warn("calculated final : " +product.getProduct_id()+" : Price :"+ finalPrice);
			productDao.updatePrice(product.getProduct_id(), finalPrice, percentage,product.getBase_price());
		}

	}
	
	public void rePrice() throws Exception 
	{
		logger.warn("RePRice");

		String sql="select p.product_id as product_id, pp.base_price as base_price, pp.profit_percent as profit_percent, p.sku as sku, tax  " +
				"from product p, product_price pp" 
			+" where p.product_id=pp.product_id";
		
		List<Product> products = productDao.loadProuctsPrice(sql);
		logger.warn("No of prods found: " + products.size());
		for (Product product : products) 
		{
			float basePrice=product.getBase_price();
			
			float basePriceWithGST = (basePrice+getShippingFee(basePrice)) * (1 + product.getTax() / 100);
			float finalPrice = basePriceWithGST * (1 + getProfitPercent(basePrice) / 100);
			logger.warn("calculated final : " +product.getProduct_id()+" : Price :"+ finalPrice);
			productDao.updatePrice(product.getProduct_id(), finalPrice, getProfitPercent(basePrice),basePrice);
		}

	}
	
	private float getShippingFee(float basePrice)
	{

		if(basePrice<=100)
		{
			return (5.00f+1.00f);//change on 1st jan 2014 5$ shippping + 1$ fixed profit
		}

		//greater than 100 add shipping cost
		return 5f;
	}

	private float getProfitPercent(float basePrice)
	{
//		if(basePrice<100)
//		{
//			return 9.0f;
//		}
//		else if (basePrice<200){
//			return 8.5f;
//		}
//		else if (basePrice<300){
//			return 8.0f;
//		}
//		else if (basePrice<400){
//			return 7.75f;
//		}
		
//		Minimum 8% pp change on 08-nov-2013
		
		//return fixed 3.25 percent profit
		return 3.25f;
	}
	
	public void updatePrice(float newPriceBasePrice, Integer prodId) throws Exception 
	{
		logger.warn("flatPriceChg");
		logger.warn("applying new price :" + newPriceBasePrice);

		String sql="select p.product_id as product_id, pp.base_price as base_price, pp.profit_percent as profit_percent, p.sku as sku, tax ,ps.supplier_id as sid " +
				"from product p, product_price pp, product_to_supplier ps" 
			+" where p.product_id='"+prodId
			+"' and p.product_id=pp.product_id" 
			+" and p.product_id=ps.product_id";
		
		List<Product> products = productDao.loadProuctsPrice(sql);
		logger.warn("No of prods found: " + products.size());
		for (Product product : products) 
		{
			float basePrice=product.getBase_price();
			logger.warn("basePrice:"+product.getBase_price());
			
			if(basePrice!=newPriceBasePrice)
			{
				mapPrice(basePrice,product);
				
//				float basePriceWithGST = (newPrice+getShippingFee(newPrice))* (1 + product.getTax() / 100);
//				float finalPrice = basePriceWithGST * (1 + product.getProfit_percent() / 100);
				logger.warn("calculated final : " +product.getProduct_id()+" : Price :"+ product.getPrice());
				productDao.updatePrice(product.getProduct_id(), product.getPrice(), product.getProfit_percent(),newPriceBasePrice);
				cacheService.addUpdateProdPriceList(prodId+"", "Old:"+product.getBase_price()+"-->new Price:"+newPriceBasePrice);
			}
			else
			{
				logger.warn("                       No price change           prodId: "+prodId);
			}

			
		}

	}
	
	public void mapPrice(String basePrice, Product product) 
	{
		mapPrice(Float.parseFloat(basePrice), product); 
	}
	
	public void mapPrice(float basePrice, Product product) {
		logger.warn("mapPrice()");
		float gst=7.0f;
		
		product.setBase_price(basePrice);
		product.setTax(gst);
		
		if(product.getSupplierId()==2)
		{
			float basePriceWithGST=basePrice*(1 + gst/100);
			float retailPrice=product.getStnRetailPrice();
			
			float pfAmt=(retailPrice-basePriceWithGST)*.75f;
			float pp=100*pfAmt/basePriceWithGST;
			product.setProfit_percent(pp);
			
			//default
			float finalPrice=basePriceWithGST+pfAmt;
			
			//ideal logic for price
			if(basePriceWithGST>499 || pfAmt>15)
			{
				finalPrice=basePriceWithGST+pfAmt;
			}
			else 
			{
				logger.warn("Skip the product");
				product.setSkipProduct(true);
			}
			
			product.setPrice(finalPrice);
			
		}
		else
		{
			float pp=getProfitPercent(basePrice);
			product.setProfit_percent(pp);
			
			float basePriceWithGST=basePrice*(1 + gst/100)+getShippingFee(basePrice);
			float finalPrice=basePriceWithGST*(1+pp/100);
			product.setPrice(finalPrice);
			
		}
		
	}

	public ProductDao getProductDao() {
		return productDao;
	}

	public void setProductDao(ProductDao productDao) {
		this.productDao = productDao;
	}

	public CacheService getCacheService()
	{
		return cacheService;
	}

	public void setCacheService(CacheService cacheService)
	{
		this.cacheService = cacheService;
	}

}
